package com.atguigu.srb.core.service.impl;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.rabbitutil.constant.MQConst;
import com.atguigu.srb.rabbitutil.service.MQService;
import com.atguigu.srb.base.dto.SmsDTO;
import com.atguigu.srb.core.enums.TransTypeEnum;
import com.atguigu.srb.core.hfb.FormHelper;
import com.atguigu.srb.core.hfb.HfbConst;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.mapper.UserBindMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.bo.TransFlowBO;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.mapper.UserAccountMapper;
import com.atguigu.srb.core.pojo.entity.UserBind;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.service.TransFlowService;
import com.atguigu.srb.core.service.UserAccountService;
import com.atguigu.srb.core.service.UserInfoService;
import com.atguigu.srb.core.util.LendNoUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户账户 服务实现类
 * </p>
 *
 * @author Bright
 * @since 2022-04-09
 */
@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Resource
    UserBindMapper userBindMapper;
    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    TransFlowService transFlowService;
    @Resource
    MQService mqService;
    @Resource
    UserInfoService userInfoService;


    @Override
    public String commitCharge(BigDecimal chargeAmt, Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        String bindCode = userInfo.getBindCode();
        //判断账户绑定状态
        Assert.notEmpty(bindCode, ResponseEnum.USER_NO_BIND_ERROR);

        QueryWrapper<UserBind> userBindQueryWrapper = new QueryWrapper<>();
        userBindQueryWrapper.eq("user_id", userId);
        UserBind userBind = userBindMapper.selectOne(userBindQueryWrapper);

        HashMap<String, Object> mapParam = new HashMap<>();
        mapParam.put("agentId", HfbConst.AGENT_ID);
        //商户充值单号
        mapParam.put("agentBillNo", LendNoUtils.getNo());
        mapParam.put("bindCode", userBind.getBindCode());
        //充值金额
        mapParam.put("chargeAmt", chargeAmt);

        mapParam.put("feeAmt", new BigDecimal(0));
        mapParam.put("notifyUrl", HfbConst.RECHARGE_NOTIFY_URL);
        mapParam.put("returnUrl", HfbConst.RECHARGE_RETURN_URL);
        mapParam.put("timestamp", RequestHelper.getTimestamp());
        mapParam.put("sign", RequestHelper.getSign(mapParam));


        return FormHelper.buildForm(HfbConst.RECHARGE_URL, mapParam);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String notify(Map<String, Object> mapParam) {

        String agentBillNo = mapParam.get("agentBillNo").toString();
        if (transFlowService.isTransFlow(agentBillNo)) {
            log.warn("已经充完值了......");
            return "success";
        }


        //充值

        BigDecimal chargeAmt = new BigDecimal(mapParam.get("chargeAmt").toString());

        String bindCode = mapParam.get("bindCode").toString();


        //修改账户金额

        baseMapper.updateAccount(bindCode, chargeAmt, new BigDecimal(0));


        //生成订单号
        TransFlowBO transFlowBO = new TransFlowBO();
        transFlowBO.setAmount(chargeAmt);
        transFlowBO.setAgentBillNo(agentBillNo);
        transFlowBO.setBindCode(bindCode);
        transFlowBO.setTransTypeEnum(TransTypeEnum.RECHARGE);
        transFlowBO.setMemo(mapParam.get("resultMsg").toString());


        transFlowService.saveTransFlow(transFlowBO);

        String mobile = userInfoService.getMobileByBindCode(bindCode);
        SmsDTO smsDTO = new SmsDTO();
        smsDTO.setMobile(mobile);
        smsDTO.setMessage("1234");

        mqService.sendMessage(
                MQConst.EXCHANGE_TOPIC_SMS,
                MQConst.ROUTING_SMS_ITEM,
                smsDTO);

        return "success";


    }

    @Override
    public BigDecimal getAccountByUserId(Long userId) {
        QueryWrapper<UserAccount> userAccountQueryWrapper = new QueryWrapper<>();
        userAccountQueryWrapper
                .select("amount")
                .eq("user_id", userId);
        List<Object> amount = baseMapper.selectObjs(userAccountQueryWrapper);
        if (amount.size() == 0) {

        }
        Assert.isTrue(amount.size() > 0, ResponseEnum.ERROR);

        return new BigDecimal(amount.get(0).toString());
    }

    @Override
    public String commitWithdraw(Long userId, BigDecimal fetchAmt) {
        //判断账号余额是否充足
        BigDecimal account = this.getAccountByUserId(userId);
        Assert.isTrue(account.compareTo(fetchAmt) >= 0, ResponseEnum.NOT_SUFFICIENT_FUNDS_ERROR);

        String bindCode = userBindMapper.getBindCodeByUserId(userId);
        HashMap<String, Object> paramMap = new HashMap<>(9);
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentBillNo", LendNoUtils.getWithdrawNo());
        paramMap.put("bindCode", bindCode);
        paramMap.put("fetchAmt", fetchAmt);
        paramMap.put("feeAmt", new BigDecimal(0));
        paramMap.put("returnUrl", HfbConst.WITHDRAW_RETURN_URL);
        paramMap.put("notifyUrl", HfbConst.WITHDRAW_NOTIFY_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        paramMap.put("sign", RequestHelper.getSign(paramMap));

        return FormHelper.buildForm(HfbConst.WITHDRAW_URL, paramMap);
    }

    @Override
    public String notifyWithdraw(Map<String, Object> paramMap) {
        //幂等性返回
        String agentBillNo = paramMap.get("agentBillNo").toString();
        Assert.isTrue(!transFlowService.isTransFlow(agentBillNo), ResponseEnum.IDEMPOTENT_RETURN);
        //修改用户账号余额
        String bindCode = paramMap.get("bindCode").toString();
        String fetchAmt = (String) paramMap.get("fetchAmt");
        baseMapper.updateAccount(bindCode, new BigDecimal(fetchAmt).negate(), new BigDecimal(0));

        //生成流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(fetchAmt),
                TransTypeEnum.WITHDRAW,
                "");
        transFlowService.saveTransFlow(transFlowBO);

        return "success";
    }

    @Override
    public UserAccount getUserAccountByUserId(Long userId) {
        QueryWrapper<UserAccount> userAccountQueryWrapper = new QueryWrapper<>();
        userAccountQueryWrapper.eq("user_id",userId);

        return baseMapper.selectOne(userAccountQueryWrapper);
    }
}
